/*
 * @Version: 1.0
 * @Autor: yuchang
 * @Date: 2023-06-12 11:40:26
 * @LastEditors: yangfumin
 * @LastEditTime: 2024-04-11 17:00:03
 * @Description:
 */
import search from '@/assets/common/search.png'
import search2 from '@/assets/common/search2.png'
import { DownloadOutlined, ImportOutlined, PlusOutlined, RedoOutlined } from '@ant-design/icons'
import { Button, DatePicker, Input, message, Popconfirm, Table, Upload } from 'antd'
import locale from 'antd/es/date-picker/locale/zh_CN'
import 'dayjs/locale/zh-cn'
import { connect } from 'dva'
import moment from 'moment'
import React from 'react'
import { importFile } from '../../services/globalService'
import { downLoadFileFunc } from '../../utils/dowmloadExcel'
import DetailsModel from '../components/DetailsModel'
import PaginationPage from '../components/Pagination'
import AddModel from './components/AddModel'
import styles from './index.less'

const { RangePicker } = DatePicker

function mapStateToProps({ globalModel, projectModel }) {
  return {
    globalModel: globalModel, //通用全局模块
    projectModel: projectModel, //项目全局模块
  }
}
@connect(mapStateToProps)

// class Tab extends React.Component{}
// class Tab extends React.Component{
//    constructor(){
//      super()//从原型上继承对应的方法和属性,this必须写在super下面
//       // //构造函数初始化数据，将需要改变的数据初始化到state中
//       this.state={
//         c2:"content ",  //之所以写上是因为默认要展示一个
//         c1:"content active",
//       }
// }
class HtmlLayouts extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      addModelOpen: false, //新增员工页面显隐
      tabs: [
        { id: 1, title: '小程序加入', content: '老莫想吃鱼' },
        { id: 2, title: '后台表单录入', content: '演员大花轿' },
        { id: 3, title: '模板批量导入', content: '你还是假唱吧' },
      ],
      i: 0,
      show1: true,
      show2: false,
      sourceStatus: 0,
      dataSelectedRowKeys: [], //表格选中数组
      modelOpen: false,
      nickName: '', //用户昵称（数据请求）
      name: '', //姓名（数据请求）
      phone: '', //手机号（数据请求）
      startTime: '', //开始时间（数据请求）
      endTime: '', //结束时间（数据请求）
      auditStatus: 1, //审核状态（数据请求）
      page: 1, //页码（数据请求）
      limit: 10, //行数（数据请求）
      listTotal: 0, //数据总数
      tableData: [],
      filterState: '',
    }
    this.options = [
      {
        value: '',
        label: '全部状态',
      },
      {
        value: 0,
        label: '审核通过',
      },
      {
        value: 1,
        label: '待审核',
      },
    ]
    ;(this.thiscolumns = []),
      (this.columns = [
        {
          title: '全部序号',
          dataIndex: 'number',
          key: 'number',
          width: 110,
          render: (text, i, val) => {
            return <div>{val + 1}</div>
          },
        },
        {
          title: '头像',
          dataIndex: 'avatar',
          key: 'avatar',
          width: 90,
          render: (text, i) => {
            return <img src={i.avatar} style={{ width: 30, height: 30, borderRadius: 15 }} />
          },
        },
        {
          title: '用户昵称',
          dataIndex: 'nickName',
          key: 'nickName',
        },
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '所属部门',
          dataIndex: 'departmentName',
          key: 'departmentName',
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          key: 'phone',
        },
        // {
        // 		 title: '会员来源',
        // 		 dataIndex: 'excelStatus',
        // 		 key: 'excelStatus',
        // 			 render: (text, i) => {
        // 			   return i.excelStatus === 0 ? "小程序" : i.excelStatus === 1 ? "模板导入"  : "后台表单录入"
        // 			 }
        // },
        {
          title: '加入时间',
          dataIndex: 'joinTime',
          key: 'joinTime',
        },
        {
          title: '状态',
          dataIndex: 'auditStatus',
          key: 'auditStatus',
          render: (text, i) => {
            return (
              <div className={i.auditStatus === 0 ? styles.audit : styles.unaudit}>
                {' '}
                {i.auditStatus === 0 ? '审核通过' : '待审核'}
              </div>
            )
          },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 220,
          render: (text, i, val) => {
            return (
              <div className={styles.operation}>
                {i.auditStatus === 0 ? (
                  <div className={styles.staff}>已审核</div>
                ) : (
                  <Popconfirm
                    placement="topRight"
                    title={'是否通过审核操作？'}
                    // description={description}
                    okText="通过"
                    cancelText="取消"
                    onConfirm={this.onConfirm.bind(this, i)}>
                    <div className={styles.unstaff}>审核通过</div>
                  </Popconfirm>
                )}
                <div className={styles.details} onClick={this.detailsClick.bind(this, i)}>
                  详情
                </div>
                {i.auditStatus !== 0 ? (
                  <Popconfirm
                    placement="topRight"
                    title={'是否驳回该用户？'}
                    // description={description}
                    okText="确认"
                    cancelText="取消"
                    onConfirm={this.deleteClick.bind(this, i)}>
                    <div className={styles.delete}>驳回</div>
                  </Popconfirm>
                ) : (
                  <div className={styles.delete2}>驳回</div>
                )}
              </div>
            )
          },
        },
      ]),
      (this.columnsNew = [
        {
          title: '全部序号',
          dataIndex: 'number',
          key: 'number',
          width: 110,
          render: (text, i, val) => {
            return <div>{val + 1}</div>
          },
        },
        {
          title: '头像',
          dataIndex: 'avatar',
          key: 'avatar',
          width: 90,
          render: (text, i) => {
            return <img src={i.avatar} style={{ width: 30, height: 30, borderRadius: 15 }} />
          },
        },
        {
          title: '用户昵称',
          dataIndex: 'nickName',
          key: 'nickName',
        },
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '所属部门',
          dataIndex: 'departmentName',
          key: 'departmentName',
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          key: 'phone',
        },
        // {
        // 		 title: '会员来源',
        // 		 dataIndex: 'excelStatus',
        // 		 key: 'excelStatus',
        // 	 render: (text, i) => {
        // 	   return i.excelStatus === 0 ? "小程序" : i.excelStatus === 1 ? "模板导入"  : "后台表单录入"
        // 	 }
        // },
        {
          title: '加入时间',
          dataIndex: 'joinTime',
          key: 'joinTime',
        },
        {
          title: '状态',
          dataIndex: 'auditStatus',
          key: 'auditStatus',
          render: (text, i) => {
            return (
              <div className={i.auditStatus === 0 ? styles.audit : styles.unaudit}>
                {' '}
                {i.auditStatus === 0 ? '已加入' : '待加入'}
              </div>
            )
          },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 220,
          render: (text, i, val) => {
            return (
              <div className={styles.operation}>
                {i.auditStatus !== 0 ? (
                  <Popconfirm
                    placement="topRight"
                    title={'是否撤销该用户？'}
                    // description={description}
                    okText="确认"
                    cancelText="取消"
                    onConfirm={this.revokeClick.bind(this, i)}>
                    <div className={styles.delete}>撤销</div>
                  </Popconfirm>
                ) : (
                  <div className={styles.delete2}>已撤销</div>
                )}
                <div className={styles.details} onClick={this.detailsClick.bind(this, i)}>
                  详情
                </div>
              </div>
            )
          },
        },
      ])
  }
  //初次渲染后调用
  componentDidMount() {
    let tenantCode = localStorage.getItem('tenantCode')
    this.getData()
  }

  //在组件从 DOM 中移除之前立刻被调用。
  componentWillUnmount() {}

  //请求数据
  getData = (sourceStatus) => {
    let { nickName, name, phone, startTime, endTime, auditStatus, page, limit } = this.state
    this.props.dispatch({
      type: 'projectModel/getStaffMsg',
      payload: {
        params: {
          nickName: nickName,
          name: name,
          phone: phone,
          startTime: startTime,
          endTime: endTime,
          auditStatus: auditStatus,
          page: page,
          limit: limit,
          sourceStatus: sourceStatus ? sourceStatus : this.state.sourceStatus,
        },
        callback: (item) => {
          if (item) {
            this.setState({
              tableData: item.list,
              listTotal: item.total,
            })
          }
        },
      },
    })
  }

  //table表格的选中
  onSelectChange = (record, data) => {
    this.setState({
      dataSelectedRowKeys: record,
    })
  }

  //多选之后的抽屉组件取消事件
  onClose = () => {
    this.setState({
      dataSelectedRowKeys: [],
    })
  }

  //详情的model组件取消事件
  onCancel = () => {
    this.setState({
      modelOpen: false,
    })
  }

  //input框搜索条件
  inputOnChange = (item, e) => {
    if (item === '用户昵称查询') this.setState({ nickName: e.target.value })
    if (item === '手机号查询') this.setState({ phone: e.target.value })
    if (item === '姓名查询') this.setState({ name: e.target.value })
  }

  //时间选中的搜索条件
  timeOnChange = (data, timeArray) => {
    this.setState({
      startTime: timeArray[0],
      endTime: timeArray[1],
    })
  }

  //多选之后审核确认事件
  password = () => {
    let { dataSelectedRowKeys } = this.state
    this.staffPatch(dataSelectedRowKeys)
  }

  search = () => {
    this.getData()
  }

  //表格详情事件
  detailsClick = (data) => {
    this.setState({
      modelOpen: true,
      detailsData: data,
    })
  }

  //审核确认事件
  onConfirm = (data) => {
    this.staffPatch([data.id])
  }

  //审核接口
  staffPatch = (data) => {
    this.props.dispatch({
      type: 'projectModel/staffPass',
      payload: {
        params: data,
        callback: (item) => {
          console.log(item, 'data')
          if (item.code === 0 && item.msg === 'success') {
            message.success('审核通过')
            this.getData()
            this.setState({
              dataSelectedRowKeys: [],
            })
          }
        },
      },
    })
  }

  //撤销按钮
  revokeClick = (data) => {
    this.props.dispatch({
      // type: 'projectModel/staffRevoke',
      type: 'projectModel/staffDelete',
      payload: {
        params: { id: data.id },
        callback: (item) => {
          if (item.code === 0 && item.msg === 'success') {
            message.success('已撤销')
            this.getData()
          } else {
            message.success(item.msg)
          }
        },
      },
    })
  }

  //驳回按钮
  deleteClick = (data) => {
    this.props.dispatch({
      type: 'projectModel/staffDelete',
      payload: {
        params: { id: data.id },
        callback: (item) => {
          if (item.code === 0 && item.msg === 'success') {
            message.success('已驳回')
            this.getData()
          }
        },
      },
    })
  }

  reset = () => {
    this.setState(
      {
        nickName: '',
        phone: '',
        name: '',
        auditStatus: '',
        startTime: '',
        endTime: '',
        page: 1,
        limit: 10,
      },
      () => {
        this.getData()
      },
    )
  }

  //table表格翻页
  handlePageChange = (page) => {
    this.setState(
      {
        page,
      },
      () => {
        this.getData()
      },
    )
  }

  //table表格
  handlePageSizeChange = (page, limit) => {
    this.setState(
      {
        page,
        limit,
      },
      () => {
        this.getData()
      },
    )
  }

  //新增蒙层页面显示
  addPeople = () => {
    this.setState({
      addModelOpen: true,
    })
  }

  //蒙层model隐藏
  onCancel = () => {
    this.setState({
      addModelOpen: false,
      modelOpen: false,
    })
  }

  //新增成功回调
  onFinish = (e) => {
    this.props.dispatch({
      type: 'projectModel/addStaff',
      payload: {
        params: {
          name: e.username,
          // phone: e.phoneNumber,
          departmentName: e.address,
        },
        callback: () => {
          this.getData()
          this.onCancel()
        },
      },
    })
  }

  customRequest = async ({ file }) => {
    const formData = new FormData()
    formData.append('file', file)
    await importFile(formData)
      .then(() => {
        message.success('上传成功！')
      })
      .catch(() => {
        message.error(`上传失败！`)
      })
  }

  //新增失败回调
  onFinishFailed = () => {
    console.log('11111111111')
  }

  render() {
    let { tabs, i } = this.state
    let {
      show1,
      show2,
      dataSelectedRowKeys,
      modelOpen,
      tableData,
      detailsData,
      nickName,
      phone,
      name,
      startTime,
      endTime,
      listTotal,
      page,
      limit,
      addModelOpen,
    } = this.state
    const rowSelection = {
      selectedRowKeys: dataSelectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        // 将数据的唯一 id 作为行 id
        disabled: record.auditStatus === 0,
      }),
      hideDefaultSelections: true,
      columnWidth: '25px',
    }
    return (
      <div className={styles.normal}>
        <div className={styles.modelTitle}>低碳审核</div>
        <div className={styles.searchBox}>
          <Input
            onChange={this.inputOnChange.bind(this, '用户昵称查询')}
            style={{ width: 140, borderRadius: 8, marginRight: 10 }}
            placeholder="用户昵称查询"
            prefix={<img style={{ width: 15, height: 15 }} src={search2} />}
            value={nickName}
          />
          <Input
            onChange={this.inputOnChange.bind(this, '手机号查询')}
            style={{ width: 140, borderRadius: 8, marginRight: 10 }}
            placeholder="手机号查询"
            prefix={<img style={{ width: 15, height: 15 }} src={search2} />}
            value={phone}
          />
          <Input
            onChange={this.inputOnChange.bind(this, '姓名查询')}
            style={{ width: 110, borderRadius: 8, marginRight: 10 }}
            placeholder="姓名查询"
            prefix={<img style={{ width: 15, height: 15 }} src={search2} />}
            value={name}
          />
          <RangePicker
            showTime
            onChange={this.timeOnChange}
            locale={locale}
            style={{ width: 288, borderRadius: 8, marginRight: 10 }}
            value={startTime && [moment(startTime, 'YYYY-MM-DD HH:mm:ss'), moment(endTime, 'YYYY-MM-DD HH:mm:ss')]}
          />
          <div className={styles.searchBtn} onClick={this.search}>
            <img src={search} style={{ marginRight: 5 }} />
            <div>查询</div>
          </div>
          <div className={styles.resetBtn} onClick={this.reset}>
            <RedoOutlined style={{ width: 15, height: 15, marginRight: 5 }} />
            <div>重置</div>
          </div>
          {this.state.sourceStatus === 2 && (
            <div style={{ position: 'absolute', display: 'flex', right: 20 }}>
              <div className={styles.searchBtn2} onClick={this.addPeople}>
                <PlusOutlined style={{ marginRight: 5 }} />
                <div>新增</div>
              </div>
            </div>
          )}
          {this.state.sourceStatus === 1 && (
            <>
              <div style={{ position: 'absolute', display: 'flex', right: 120 }}>
                <div className={styles.searchBtn2} onClick={() => downLoadFileFunc()}>
                  <DownloadOutlined style={{ marginRight: 5 }} />
                  <div>模板下载</div>
                </div>
              </div>
              <div style={{ position: 'absolute', display: 'flex', right: 20 }}>
                <Upload name={'file'} showUploadList={false} customRequest={(file) => this.customRequest(file)}>
                  <div className={styles.searchBtn2}>
                    <ImportOutlined style={{ marginRight: 5 }} />
                    <div>用户导入</div>
                  </div>
                </Upload>
              </div>
            </>
          )}
        </div>

        <div className={styles.searchBox}>
          {tabs.map((ele, index) => (
            <div
              key={ele.id}
              //三元运算符
              className={styles.tabBtn}
              className={i == index ? ` ${styles.tabBtn}  ${styles.tabBtnOn} ` : styles.tabBtn}
              // setState方法的参数
              // 第一个参数：对象（最常用）、函数  （得到修改之前的旧值）
              // 第二个参数：回调函数  （可以得到修改以后最新的值）
              onClick={() => {
                this.setState({
                  i: index,
                })
                if (index == 0) {
                  this.setState(
                    {
                      show1: true,
                      show2: false,
                      sourceStatus: 0,
                    },
                    () => {
                      this.getData(0)
                    },
                  )
                } else if (index == 1) {
                  this.setState(
                    {
                      show1: false,
                      show2: true,
                      sourceStatus: 2,
                    },
                    () => {
                      this.getData(2)
                    },
                  )
                } else {
                  this.setState(
                    {
                      show1: false,
                      show2: true,
                      sourceStatus: 1,
                    },
                    () => {
                      this.getData(1)
                    },
                  )
                }
              }}>
              {ele.title}
            </div>
          ))}
        </div>
        {this.state.sourceStatus === 0 && (
          <Popconfirm
            disabled={this.state.dataSelectedRowKeys?.length < 1}
            title={'确认将已选中的用户全部审核通过?'}
            onConfirm={this.password}
            onCancel={this.onClose}
            okText="全部审核通过"
            cancelText="取消">
            <Button
              style={{
                float: 'right',
                marginBottom: '20px',
              }}
              disabled={this.state.dataSelectedRowKeys?.length < 1}>
              批量审核
            </Button>
          </Popconfirm>
        )}
        {show1 && (
          <Table
            scroll={this.state.sourceStatus === 0 ? { y: 'calc(100vh - 372px)' } : { y: 'calc(100vh - 320px)' }}
            pagination={false}
            rowSelection={rowSelection}
            columns={this.columns}
            dataSource={tableData}
            rowKey="id"
          />
        )}
        {show2 && (
          <Table
            scroll={{ y: 'calc(100vh - 320px)' }}
            pagination={false}
            rowSelection={rowSelection}
            columns={this.columnsNew}
            dataSource={tableData}
            rowKey="id"
          />
        )}

        <PaginationPage
          listTotal={listTotal}
          pageSize={limit}
          currentPage={page}
          handlePageChange={this.handlePageChange}
          handlePageSizeChange={this.handlePageSizeChange}
        />
        {modelOpen && <DetailsModel detailsData={detailsData} modelOpen={modelOpen} onCancel={this.onCancel} />}
        {addModelOpen && (
          <AddModel
            addModelOpen={addModelOpen}
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
            onCancel={this.onCancel}
          />
        )}
      </div>
    )
  }
}
export default HtmlLayouts
